package client;


import java.util.Properties;

import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.objectweb.joram.client.jms.Topic;

public class Subscriber extends Thread {

	private String fed = null;
	static Context ictx = null;
	private MsgListener msgl = null;
	private Object lock = null;
	private Properties env = null;
	private String serverJMS = null;

	public Subscriber(String server,String fed2, Object lock2, MsgListener msglst) {
		fed = fed2;
		lock = lock2;
		msgl = msglst;
		serverJMS = server;
	}


	public void run() {
		try {
			// Creo le variabili di connessione e sessione per agganciarmi a
			// una federazione
			env = new Properties();
			env.put("java.naming.factory.initial",
			"fr.dyade.aaa.jndi2.client.NamingContextFactory");
			env.put("java.naming.factory.host", serverJMS);
			env.put("java.naming.factory.port", "16400");
			ictx = new InitialContext(env);
			Topic topic = (Topic) ictx.lookup(fed);
			TopicConnectionFactory tcf = (TopicConnectionFactory) ictx
					.lookup(fed + "tcf");
			ictx.close();
			TopicConnection tc = tcf.createTopicConnection();
			TopicSession ts = tc.createTopicSession(true,
					Session.SESSION_TRANSACTED);
			
			// Creo il subscriber e mi metto in wait.
			TopicSubscriber tsub = ts.createSubscriber(topic);

			tsub.setMessageListener(msgl);
			tc.start();
			synchronized (lock) {
				lock.wait();
			}
			tc.close();
			System.out.println("Esco dalla federazione");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}